package com.ftar.urgent.ui;

import android.os.Bundle;
import android.os.Handler;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;

import androidx.databinding.DataBindingUtil;
import androidx.databinding.ViewDataBinding;
import androidx.lifecycle.Observer;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.ftar.urgent.R;
import com.ftar.urgent.adapter.CatalogAdapter;
import com.ftar.urgent.api.resp.GetIndustryTreeResp;
import com.ftar.urgent.constant.ArouterConstant;
import com.ftar.urgent.databinding.ActivityCatalogSecondBinding;
import com.ftar.urgent.viewmodel.CommonEvent;
import com.ftar.urgent.viewmodel.SP_Constants;
import com.ftar.urgent.viewmodel.SecondActivityModel;
import com.ftar.urgent.voice.OffLineVoiceCmd;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.List;

/**
 * @author: wei.jin
 * @date: 2023/7/4
 * @email: wei.jin@fanttec.com
 * @description：
 */
@Route(path = ArouterConstant.CATALOG_SECOND_ACTIVITY)
public class CatalogSecondActivity extends BaseActivity {

    private ActivityCatalogSecondBinding mBinding;
    private CatalogAdapter mCatalogAdapter;
    private SecondActivityModel mModel;

    @Autowired
    public int parentId;

    @Autowired
    public int parentCode;

    @Override
    protected ViewDataBinding getChildBinding() {
        mBinding = DataBindingUtil.inflate(getLayoutInflater(), R.layout.activity_catalog_second, null, false);
        mBinding.setHandler(this);
        return mBinding;
    }

    @Override
    protected String voiceHint() {
        int size = 0;
        if(mCatalogAdapter != null){
            size = mCatalogAdapter.getCount();
        }
        int pageSize = 0;
        if (mModel != null) {
            pageSize = mModel.getPageSize();
        }
        if (size > pageSize) {
            return "打开第1/2/3/4/5/6个";
        } else if (size == 0) {
            return "无数据";
        } else {
            StringBuffer sb = new StringBuffer();
            sb.append("打开第");
            for (int i = 1; i <= size; i++) {
                sb.append(i).append("/");
            }
            String substring = sb.substring(0, sb.length() - 1);
            return substring + "个";
        }
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ARouter.getInstance().inject(this);
        mBinding.setLifecycleOwner(this);
        init();
        observe();
    }

    private void observe() {
        mModel.mRootList.observe(mBinding.getLifecycleOwner(), new Observer<List<GetIndustryTreeResp>>() {
            @Override
            public void onChanged(List<GetIndustryTreeResp> v) {
                mCatalogAdapter.refreshList(v);
                setVoiceHint();
            }
        });
    }

    private void init() {
        mRootBind.previousPage.setVisibility(View.VISIBLE);
        mRootBind.nextPage.setVisibility(View.VISIBLE);
        mRootBind.backDesktop.setVisibility(View.VISIBLE);
        mRootBind.clickBackBtn.setVisibility(View.VISIBLE);
        mModel = new SecondActivityModel(this, mBinding, parentId, parentCode);
        mCatalogAdapter = new CatalogAdapter(mBinding.getHandler(), mModel.getmRootList());
        mBinding.catalogGridview.setAdapter(mCatalogAdapter);
        mBinding.catalogGridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
                itemClick(position);
            }
        });
        mModel.initIndustryTree();
    }

    /**
     * Catalog item click by keyClick or voice command
     *
     * @param pos
     */
    private void itemClick(int pos) {
        List<GetIndustryTreeResp> getIndustryTreeResps = mModel.getmRootList();
        if (getIndustryTreeResps != null && !getIndustryTreeResps.isEmpty()) {
            GetIndustryTreeResp industryTreeResp = getIndustryTreeResps.get(pos);
            ARouter.getInstance()
                    .build(ArouterConstant.CATALOG_THIRD_ACTIVITY)
                    .withInt("currentId", industryTreeResp.getId())
                    .withInt("currentCode", industryTreeResp.getCode())
                    .withInt("parentId", parentId)
                    .withInt("parentCode", parentCode)
                    .navigation();
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        long selectedId = mCatalogAdapter.getmSelectedId();
        switch (keyCode) {
            case KeyEvent.KEYCODE_DPAD_LEFT:
                // 第一个 且 前面还有页
                if (selectedId == 0 && mModel.getCurrentPage() != 1) {
                    setItemSelected(mModel.getPageSize()-1);
                    mModel.goPreviousPage();
                    break;
                }
                if (selectedId > 0) {
                    selectedId -= 1;
                }
                setItemSelected((int) selectedId);
                break;
            case KeyEvent.KEYCODE_DPAD_RIGHT:
                // 最后一个 且 后面还有页
                if (selectedId == mCatalogAdapter.getCount()-1 && mModel.getCurrentPage() < mModel.getTotalPage()) {
                    setItemSelected(0);
                    mModel.goNextPage();
                    break;
                }
                if (selectedId < mCatalogAdapter.getCount()-1) {
                    selectedId += 1;
                }
                setItemSelected((int) selectedId);
                break;
            case KeyEvent.KEYCODE_ENTER:
            case KeyEvent.KEYCODE_F9:
                itemClick(Long.valueOf(selectedId).intValue());
                break;
            default:
                break;
        }
        return super.onKeyDown(keyCode, event);
    }

    private void onAsrCommand(String command) {
        if (!isActivityVisible()) {
            return;
        }
        switch (command) {
            case OffLineVoiceCmd.OfflineVoice.SETTING_SELECT_PROJECT_1:
                goItem(1);
                break;
            case OffLineVoiceCmd.OfflineVoice.SETTING_SELECT_PROJECT_2:
                goItem(2);
                break;
            case OffLineVoiceCmd.OfflineVoice.SETTING_SELECT_PROJECT_3:
                goItem(3);
                break;
            case OffLineVoiceCmd.OfflineVoice.SETTING_SELECT_PROJECT_4:
                goItem(4);
                break;
            case OffLineVoiceCmd.OfflineVoice.SETTING_SELECT_PROJECT_5:
                goItem(5);
                break;
            case OffLineVoiceCmd.OfflineVoice.SETTING_SELECT_PROJECT_6:
                goItem(6);
                break;
            case OffLineVoiceCmd.OfflineVoice.GLOBAL_BACK_DESKTOP:
                backDeskTop();
                return;
            case OffLineVoiceCmd.OfflineVoice.GLOBAL_PAGE_PRE:
                //上一页
                mModel.goPreviousPage();
                return;
            case OffLineVoiceCmd.OfflineVoice.GLOBAL_PAGE_NEXT:
                //下一页
                mModel.goNextPage();
                return;
            case OffLineVoiceCmd.OfflineVoice.GLOBAL_BACK:
                // 返回
                backPage();
                return;
        }

    }

    private void goItem(int pos){
        final int focusPos = pos - 1;
        setItemSelected(focusPos);
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                itemClick(focusPos);
            }
        }, 500);
    }

    /**
     * 返回上一层
     */
    private void backPage() {
        this.finish();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onCommonEvent(CommonEvent event) {
        if(!event.getmClass().equals(this.getClass().getName())){
            return;
        }
        switch (event.getMsg()) {
            case SP_Constants.EVENT_COMMAND_ASR:
                String command = event.getData();
                onAsrCommand(command);
                break;
            default:
                break;
        }
    }

    private void setItemSelected(int pos) {
        mBinding.catalogGridview.setSelection(pos);
        mCatalogAdapter.setSelectItem(pos);
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public void onPause() {
        super.onPause();
    }
}
